package com.molin.xml;

import com.sun.security.jgss.GSSUtil;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.ArrayList;
import java.util.List;

public class XmlParse {
    public static void main(String[] args) throws DocumentException {
        ArrayList<Student> students=new ArrayList<>();

        //1.获取一个解析器对象
        SAXReader saxReader=new SAXReader();
        //2.利用解析器把XML文件加载到内存中，并返回一个文档对象
        Document document = saxReader.read("D:\\IdeaProjects\\BasicCode\\mIdeaTest\\src\\com\\molin\\xml\\student.xml");
        //3.获取到根标签
        Element rootElement = document.getRootElement();
        //4.通过根标签，获取student标签及其相关内容
        List<Element> elements = rootElement.elements("student");
        for (Element element : elements) {
            //element依次表示每一个student标签

            //获取id这个属性
            Attribute attribute = element.attribute("id");
            //获取id这个属性值
            String id = attribute.getValue();

            //获取name标签
            Element nameElement = element.element("name");
            //获取name标签的标签体内容
            String name = nameElement.getText();

            //获取age标签
            Element ageElement = element.element("age");
            //获取age标签的标签体内容
            String age = ageElement.getText();

            Student s=new Student(id,name,Integer.parseInt(age));
            students.add(s);
        }

        for (Student student : students) {
            System.out.println(student.toString());
        }
    }
}
